package com.example.supermonkeysm.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;

@Data
public class Result<T> implements Serializable {
    private int code;
    private T data;
    private String msg;

    public static <T> Result<T> success(T data, String msg) {
        Result<T> res = new Result<>();
        res.setCode(200);
        res.setData(data);
        res.setMsg(msg);
        return res;
    }

    public static <T> Result<T> success(String msg) {
        Result<T> res = new Result<>();
        res.setCode(200);
        res.setData((T) "");
        res.setMsg(msg);
        return res;
    }

    public static <T> Result<T> error(int code, String msg) {
        Result<T> res = new Result<>();
        res.setCode(code);
        res.setData((T) "");
        res.setMsg(msg);
        return res;
    }

    public static <T> Result<T> error(String msg) {
        Result<T> res = new Result<>();
        res.setCode(400);
        res.setData((T) "");
        res.setMsg(msg);
        return res;
    }

    public static <T> Result<T> error(T data, String msg) {
        Result<T> res = new Result<>();
        res.setCode(400);
        res.setData(data);
        res.setMsg(msg);
        return res;
    }

    public static void customResult(HttpServletResponse response, int code, String msg) throws IOException {
        Map<String, Object> map = new TreeMap<>();
        map.put("code", code);
        map.put("data", "");
        map.put("msg", msg);
        response.setContentType("application/json;charset=UTF-8");
        String json = new ObjectMapper().writeValueAsString(map);
        response.getWriter().write(json);
    }

    public static void customResult(HttpServletResponse response, Map<String, Object> map) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String json = new ObjectMapper().writeValueAsString(map);
        response.getWriter().write(json);
    }
}
